package common;

import common.Service.CountService;
import common.correspondence.Client;
import common.correspondence.Message;
import common.correspondence.Server;

import java.net.InetAddress;
import java.net.UnknownHostException;


public class Port implements PortInterface {
    public String portName;
    public String name;
    int srcSrvPort;
    int dstSrvPort;
    InetAddress dstIp;
    InetAddress srcIp;

    Server srv;
    Client cli;

    CountService csServer;
    CountService csClient;

    public Device device;

    public Port(String portName, String srcSrvPort, String dstSrvPort, String dstIpStr, Device d){
        try {
            dstIp = InetAddress.getByAddress(Utility.ip2Bytes(dstIpStr));
            srcIp = InetAddress.getByAddress(Utility.ip2Bytes(d.ip));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        this.srcSrvPort = Integer.parseInt(srcSrvPort);
        this.dstSrvPort = Integer.parseInt(dstSrvPort);
        device = d;
        this.portName = portName;
        this.name = d.name + ":" + portName;
        srv = new Server(this.srcIp, this.srcSrvPort, this);
        cli = new Client(this.srcIp, this.dstIp, this.dstSrvPort, this);


    }

    @Override
    public void send(Message msg){
        cli.send(msg);
    }

//    public void send(CIBIO cibOut, NodePointer from, NodePointer to, String id){
//        try {
//            csClient.sendCount(cibOut, from, to, id);
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void receive(Message msg){
        device.receive(msg);
    }

    @Override
    public void close(){
        cli.close();
        srv.close();
    }

    @Override
    public boolean isAlready(){
        return cli.isAlready() && srv.isAlready();
    }

    @Override
    public void testLink() {
        cli.test();
    }

    @Override
    public String toString() {
        return "Port " + portName;
    }
}
